package com.streaminggbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.streaminggbs.common.base.BaseQueryBean;
import com.streaminggbs.common.base.ErrorCodeException;
import com.streaminggbs.common.base.ReturnBean;
import com.streaminggbs.common.config.StaticConfig;
import com.streaminggbs.entity.LoginUser;
import com.streaminggbs.entity.SysAuthUser;
import com.streaminggbs.interfaces.SysAuthUserService;
import com.streaminggbs.common.utils.DateUtil;
import com.streaminggbs.common.utils.IDManager;
import com.streaminggbs.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author LiLin
 * @Date 2020/9/15 9:23
 * @Description 用户管理
 */
@Api(tags = {"用户管理接口"})
@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private SysAuthUserService sysAuthUserService;

    @ApiOperation(value = "获取用户信息列表", notes = "获取用户信息列表")
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResponseEntity<ReturnBean> list(
            @ApiParam(value = "分页参数，从1开始") @RequestParam(value = "page", required = false, defaultValue = "1") int page,
            @ApiParam(value = "分页用") @RequestParam(value = "limit", required = false, defaultValue = "10") int limit,
            BaseQueryBean baseQueryBean) {

        PageInfo<SysAuthUser> list = new PageInfo<>();
        try {
            list = sysAuthUserService.selectPageList(baseQueryBean, page, limit);
        } catch (Exception e) {
            log.error("获取当前的用户信息异常!{}",e);
        }
        return new ResponseEntity<>(new ReturnBean(list), HttpStatus.OK);
    }

    @ApiOperation(value = "添加用户", notes = "添加用户")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ReturnBean add(
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true) String deptid,
            @ApiParam(value = "登录名") @RequestParam(value = "loginname", required = true) String loginname,
            @ApiParam(value = "登录密码") @RequestParam(value = "password", required = true) String password,
            @ApiParam(value = "姓名") @RequestParam(value = "username", required = true) String username,
            @ApiParam(value = "用户组id（角色ID）") @RequestParam(value = "usergroupid", required = true) String usergroupid,
            @ApiParam(value = "性别（1 男 2 女）") @RequestParam(value = "usersex", required = false) Integer usersex,
            @ApiParam(value = "手机号") @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(value = "固定电话") @RequestParam(value = "telephone", required = false) String telephone,
            @ApiParam(value = "邮箱") @RequestParam(value = "email", required = false) String email,
            @ApiParam(value = "用户编码（用于授权）") @RequestParam(value = "userNumber", required = false) String userNumber,
            @ApiParam(value = "有效期") @RequestParam(value = "validtimeStr", required = false) String validtimeStr,
            SysAuthUser entity
    ) {
        log.info("======添加用户======>deptid:" + deptid + "，loginname:" + loginname + "，password:" + password + "，username:" + username
                + "，usergroupid:" + usergroupid + "，usersex:" + usersex + "，mobile:" + mobile + "，telephone:" + telephone
                + "，email:" + email + "，userNumber:" + userNumber + "，validtimeStr:" + validtimeStr);
        try {
            if(!StringUtil.isEmpty(validtimeStr)){
                entity.setValidtime(DateUtil.parse(validtimeStr, DateUtil.PATTERN_CLASSICAL_SIMPLE));
            }

            //验证用户是否已存在
            SysAuthUser paramInfo = new SysAuthUser();
            paramInfo.setLoginname(loginname);
            SysAuthUser oldInfo = sysAuthUserService.selectByOther(paramInfo);
            if(oldInfo != null){
                return new ReturnBean(-1, "登录名已存在");
            }

            entity.setUserid(IDManager.nextId());
            sysAuthUserService.save(entity);

            return new ReturnBean("保存成功");
        }catch (Exception e){
            log.error("==用户管理==添加用户报错==",e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "编辑用户", notes = "编辑用户")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ReturnBean edit(
            @ApiParam(value = "用户ID") @RequestParam(value = "userid", required = true) String userid,
            @ApiParam(value = "机构ID") @RequestParam(value = "deptid", required = true) String deptid,
            @ApiParam(value = "登录名") @RequestParam(value = "loginname", required = true) String loginname,
            @ApiParam(value = "姓名") @RequestParam(value = "username", required = true) String username,
            @ApiParam(value = "用户组id（角色ID）") @RequestParam(value = "usergroupid", required = true) String usergroupid,
            @ApiParam(value = "性别（1 男 2 女）") @RequestParam(value = "usersex", required = false) Integer usersex,
            @ApiParam(value = "手机号") @RequestParam(value = "mobile", required = false) String mobile,
            @ApiParam(value = "固定电话") @RequestParam(value = "telephone", required = false) String telephone,
            @ApiParam(value = "邮箱") @RequestParam(value = "email", required = false) String email,
            @ApiParam(value = "用户编码（用于授权）") @RequestParam(value = "userNumber", required = false) String userNumber,
            @ApiParam(value = "有效期") @RequestParam(value = "validtimeStr", required = false) String validtimeStr,
            @ApiParam(value = "状态（停用/激活状态）1 激活 2 停用") @RequestParam(value = "status", required = false) Integer status,
            @ApiParam(value = "登录密码") @RequestParam(value = "password", required = false) String password,
            SysAuthUser entity
    ) {
        log.info("======编辑用户======>userid:" + userid + "，deptid:" + deptid + "，loginname:" + loginname + "，username:" + username
                + "，usergroupid:" + usergroupid + "，usersex:" + usersex + "，mobile:" + mobile + "，telephone:" + telephone
                + "，email:" + email + "，userNumber:" + userNumber + "，validtimeStr:" + validtimeStr + "，status:" + status
                + "，password:" + password);
        try {
            if(!StringUtil.isEmpty(validtimeStr)){
                entity.setValidtime(DateUtil.parse(validtimeStr, DateUtil.PATTERN_CLASSICAL_SIMPLE));
            }
            if(StringUtil.isEmpty(password)){
                entity.setPassword(null);
            }

            //验证用户是否已存在
            SysAuthUser paramInfo = new SysAuthUser();
            paramInfo.setLoginname(loginname);
            SysAuthUser oldInfo = sysAuthUserService.selectByOther(paramInfo);
            if(oldInfo != null && !userid.equals(oldInfo.getUserid())){
                return new ReturnBean(-1, "登录名已存在");
            }

            sysAuthUserService.updateNotNull(entity);

            return new ReturnBean("保存成功");
        }catch (Exception e){
            log.error("==用户管理==编辑用户报错==",e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "删除用户", notes = "删除用户")
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public ReturnBean delete(
            @ApiParam(value = "用户ID") @RequestParam(value = "userid", required = true) String userid
    ) {
        log.info("======删除用户======>userid:" + userid);
        try {
            sysAuthUserService.delete(userid);

            return new ReturnBean("保存成功");
        }catch (Exception e){
            log.error("==用户管理==删除用户报错==",e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "获取用户信息", notes = "获取用户信息")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
    public ReturnBean getUserInfo(HttpServletRequest request
    ) {
        try {
            HttpSession session = request.getSession();
            if(session == null){
                return new ReturnBean(-1, "用户未登录");
            }
            SysAuthUser user = (SysAuthUser) session.getAttribute("user");
            if(user == null){
                return new ReturnBean(-1, "用户未登录");
            }

            Map<String, Object> resultMap = new HashMap<>();
            JSONObject userObj = new JSONObject();
            userObj.put("Id", user.getUserid());
            userObj.put("Name", user.getUsername());
            resultMap.put("userInfo", userObj);

            resultMap.put("menus", session.getAttribute("menus"));
            resultMap.put("buttons", session.getAttribute("buttons"));

            return new ReturnBean(resultMap);
        }catch (Exception e){
            log.error("==用户管理==获取用户信息报错==",e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }

    @ApiOperation(value = "修改密码", notes = "修改密码")
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.POST)
    public ReturnBean modifypassword(
            @ApiParam(value = "原密码") @RequestParam(value = "oldpassword", required = true) String oldpassword,
            @ApiParam(value = "新密码") @RequestParam(value = "newpassword", required = true) String newpassword,
            @ModelAttribute LoginUser loginUser
    ) {
        log.info("======修改密码======>userid:" + loginUser.getSysUser().getUserid() + "，oldpassword:" + oldpassword + "，newpassword:" + newpassword);
        try {
            //验证原密码的正确性
            SysAuthUser paramInfo = new SysAuthUser();
            paramInfo.setUserid(loginUser.getSysUser().getUserid());
            paramInfo.setPassword(oldpassword);
            SysAuthUser oldInfo = sysAuthUserService.selectByOther(paramInfo);
            if(oldInfo == null){
                return new ReturnBean(-1, "原密码错误");
            }

            SysAuthUser entity = new SysAuthUser();
            entity.setUserid(loginUser.getSysUser().getUserid());
            entity.setPassword(newpassword);
            sysAuthUserService.updateNotNull(entity);

            return new ReturnBean("保存成功");
        }catch (Exception e){
            log.error("==用户管理==修改密码报错==",e);
            throw new ErrorCodeException(StaticConfig.SYSTEM_ERROR);
        }
    }
}
